import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:yinshui_caiying/http/apis.dart';
import 'package:yinshui_caiying/http/http.dart';
import 'package:yinshui_caiying/model/loginInfo_model.dart';
import 'package:yinshui_caiying/model/result_model.dart';
import 'package:yinshui_caiying/model/userInfo_result_model.dart';
import 'package:yinshui_caiying/pages/item/item_list.dart';
import 'package:yinshui_caiying/services/common_services.dart';
import 'package:yinshui_caiying/services/user_services.dart';
import 'package:yinshui_caiying/utils/colors.dart';
import 'package:yinshui_caiying/utils/icons.dart';
import 'package:yinshui_caiying/utils/screen.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:yinshui_caiying/pages/project/project_list.dart';
import 'package:yinshui_caiying/widgets/my_dialog.dart';

class LoginPage extends StatelessWidget {
  LoginController vm = Get.put(LoginController());
  UserService userService = Get.find();
  final _passwordFoucusNode = FocusNode().obs;
  final showPassword = false.obs;
  //输入框
  Widget loginInput(
      {bool isPassword = false,
      String placeholder = '',
      IconData icon = MyIcons.username,
      TextEditingController? controller,
      void Function(String)? onChanged,
      void Function(String)? onFieldSubmitted,
      FocusNode? focusNode,
      bool request = false,
      bool hasShow = false,
      String? initValue}) {
    final hasPassword = false.obs;
    hasPassword.value = isPassword;
    if (controller == null) {
      controller = TextEditingController(text: initValue);
    } else {}
    _passwordFoucusNode.value.addListener(() {
      _passwordFoucusNode(_passwordFoucusNode.value);
    });
    return Container(
      width: 685.w,
      // height: setHeight(80),
      decoration: BoxDecoration(
          border: Border(
              bottom:
                  BorderSide(width: 1.h, color: Color.fromRGBO(0, 0, 0, 0.3)))),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Icon(
            icon,
            size: 44.w,
          ),
          Expanded(
            flex: 1,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Expanded(
                  child: Container(
                      padding: EdgeInsets.only(left: 31.w),
                      child: Obx(() => TextFormField(
                          focusNode: focusNode,
                          controller: controller,
                          obscureText: hasPassword.value,
                          onChanged: onChanged,
                          onFieldSubmitted: onFieldSubmitted,
                          keyboardType: TextInputType.name,
                          textAlignVertical: TextAlignVertical.top,
                          style: TextStyle(height: 3.w),
                          decoration: InputDecoration.collapsed(
                            hintText: placeholder,
                          ),
                          validator: request
                              ? (value) {
                                  if (value == '') {
                                    return '请输入' + placeholder;
                                  } else {
                                    return null;
                                  }
                                }
                              : null))),
                ),
                Obx(() {
                  if (hasShow &&
                      vm.userService.logininfo.value.password.length > 0 &&
                      _passwordFoucusNode.value.hasFocus) {
                    return Container(
                      width: 44.w,
                      height: 44.w,
                      child: IconButton(
                          padding: EdgeInsets.zero,
                          iconSize: 44.w,
                          icon: showPassword.value
                              ? Icon(
                                  Icons.visibility_off,
                                  size: 44.w,
                                )
                              : Icon(
                                  Icons.visibility,
                                  size: 44.w,
                                ),
                          onPressed: () {
                            showPassword.toggle();
                            hasPassword.toggle();
                          }),
                    );
                  } else {
                    return Container(
                      child: showPassword.value ? Text('') : Text(''),
                    );
                  }
                })
              ],
            ),
          )
        ],
      ),
    );
  }

  //提交按钮
  Widget loginBtton() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Container(
          width: 724.w,
          height: 145.h,
          child: TextButton(
            style: ButtonStyle(
                shape: MaterialStateProperty.all(RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(72.w),
                )),
                backgroundColor:
                    MaterialStateProperty.all(Color.fromRGBO(11, 193, 173, 1))),
            child: Text(
              '提  交',
              style: TextStyle(
                  fontSize: 48.sp,
                  fontWeight: FontWeight.w400,
                  color: Colors.white),
            ),
            onPressed: () {
              if (_formKey.currentState!.validate()) {
                print('提交成功');

                vm._login();
              }

              print('object');
            },
          ),
        )
      ],
    );
  }

  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: PreferredSize(
            child: Container(
              height: 0,
              color: MyColors.main,
            ),
            preferredSize: Size(0, 0)),
        body: SafeArea(
            child: Form(
                key: _formKey,
                child: ListView(
                  children: [
                    Column(
                      children: [
                        Container(
                          child: null,
                          height: 900.h,
                          width: 1.sw,
                          decoration: BoxDecoration(
                              image: DecorationImage(
                                  image: AssetImage(
                                      'assets/images/login/login-bj.png'),
                                  fit: BoxFit.cover)),
                        ),
                        SizedBox(
                          height: 150.h,
                        ),
                        loginInput(
                          placeholder: '用户名',
                          request: true,
                          onChanged: (value) {
                            userService.logininfo.update((val) {
                              val!.username = value;
                            });
                          },
                          onFieldSubmitted: (value) {
                            _formKey.currentState!.validate();
                            FocusScope.of(context)
                                .requestFocus(_passwordFoucusNode.value);
                          },
                          controller: vm.userService.username_c,
                          // initValue: userService.logininfo.value.username
                        ),
                        SizedBox(
                          height: setHeight(119),
                        ),
                        loginInput(
                            request: true,
                            placeholder: '密码',
                            isPassword: true,
                            icon: MyIcons.password,
                            onChanged: (value) {
                              userService.logininfo.update((val) {
                                val!.password = value;
                              });
                            },
                            onFieldSubmitted: (value) {
                              if (_formKey.currentState!.validate()) {
                                print('提交成功');

                                vm._login();
                              }
                            },
                            focusNode: _passwordFoucusNode.value,
                            controller: vm.userService.password_c,
                            hasShow: true),
                        SizedBox(
                          height: 30.h,
                        ),
                        Obx(() => Container(
                              height: 65.h,
                              width: 685.w,
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.end,
                                crossAxisAlignment: CrossAxisAlignment.center,
                                children: [
                                  Text('记住密码'),
                                  Checkbox(
                                    activeColor: MyColors.main,
                                    value: userService
                                        .logininfo.value.rememberPassword,
                                    onChanged: (value) {
                                      userService.logininfo.update((val) {
                                        val!.rememberPassword = value!;
                                      });
                                    },
                                  ),
                                ],
                              ),
                            )),
                        SizedBox(
                          height: 60.h,
                        ),
                        loginBtton()
                      ],
                    )
                  ],
                ))));
  }
}

class LoginController extends GetxController {
  UserService userService = Get.find();

  @override
  void onInit() {
    super.onInit();
  }

  _login() async {
    try {
      MyDialog.showLoading(msg: '登陆中...');
      var res = await Http().post(ApiSystem.SYSTEM_USER_LOGIN, data: {
        'account': userService.logininfo.value.username,
        'password': userService.logininfo.value.password
      });
      SmartDialog.dismiss();

      UserInfoReslutModel result = UserInfoReslutModel.fromJson(res);
      if (result.code == 200) {
        ///加载公共服务
        await Get.putAsync(() => CommonService().init());
        SmartDialog.showToast('登录成功');
        userService.setUserInfoData(data: result.content.data);
        if (userService.logininfo.value.rememberPassword) {
          userService.setLoginInfoData();
        } else {
          userService.removeLoginInfoData();
        }
        Get.off(() => ItemListPage());
      } else {
        SmartDialog.showToast(result.message);
      }
    } catch (e) {
      print(e);
    }
  }
}
